import React, { useState } from 'react';
import { useRemediation } from '@/contexts/RemediationContext';
import { showMessage } from '@/components/common/MessageTip';
import StatisticsCards from './StatisticsCards';
import RemediationList from './RemediationList';
import RemediationForm from './RemediationForm';
import { type RemediationItem, type RemediationFormData } from '@/types/Remediation';

// 模态框组件
interface ModalProps {
  isOpen: boolean;
  onClose: () => void;
  children: React.ReactNode;
}

const Modal: React.FC<ModalProps> = ({ isOpen, onClose, children }) => {
  if (!isOpen) return null;
  
  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-background rounded-lg shadow-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <div className="absolute top-4 right-4">
          <button
            onClick={onClose}
            className="p-1 hover:bg-muted rounded-full transition-colors"
          >
            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        {children}
      </div>
    </div>
  );
};

// 确认对话框组件
interface ConfirmDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onConfirm: () => void;
  title: string;
  message: string;
}

const ConfirmDialog: React.FC<ConfirmDialogProps> = ({
  isOpen,
  onClose,
  onConfirm,
  title,
  message,
}) => {
  if (!isOpen) return null;
  
  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-background rounded-lg shadow-lg p-6 max-w-md w-full">
        <h3 className="text-lg font-semibold mb-2">{title}</h3>
        <p className="text-muted-foreground mb-6">{message}</p>
        <div className="flex justify-end space-x-3">
          <button
            onClick={onClose}
            className="px-4 py-2 border rounded-md hover:bg-muted transition-colors"
          >
            取消
          </button>
          <button
            onClick={() => {
              onConfirm();
              onClose();
            }}
            className="px-4 py-2 bg-destructive text-destructive-foreground rounded-md hover:bg-destructive/90 transition-colors"
          >
            确认删除
          </button>
        </div>
      </div>
    </div>
  );
};

// 右侧面板组件
interface RightPanelProps {}

const RightPanel: React.FC<RightPanelProps> = () => {
  const { 
    stats, 
    addRemediationItem, 
    updateRemediationItem, 
    deleteRemediationItem,
    exportReport
  } = useRemediation();
  
  // 模态框状态
  const [isFormModalOpen, setIsFormModalOpen] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [formMode, setFormMode] = useState<'create' | 'edit'>('create');
  const [currentItem, setCurrentItem] = useState<RemediationItem | null>(null);
  const [itemToDelete, setItemToDelete] = useState<string | null>(null);
  
  // 打开创建表单
  const openCreateForm = () => {
    setFormMode('create');
    setCurrentItem(null);
    setIsFormModalOpen(true);
  };
  
  // 打开编辑表单
  const openEditForm = (item: RemediationItem) => {
    setFormMode('edit');
    setCurrentItem(item);
    setIsFormModalOpen(true);
  };
  
  // 打开删除确认框
  const openDeleteConfirm = (id: string) => {
    setItemToDelete(id);
    setIsDeleteModalOpen(true);
  };
  
  // 处理表单提交
  const handleFormSubmit = async (data: RemediationFormData) => {
    try {
      if (formMode === 'create') {
        const newItem = await addRemediationItem(data);
        if (newItem) {
          showMessage('success', '整改项创建成功');
          setIsFormModalOpen(false);
        } else {
          showMessage('warning', '整改项创建未完成，请重试');
        }
      } else if (formMode === 'edit' && currentItem) {
        const updatedItem = await updateRemediationItem(currentItem.id, {
          title: data.title,
          suggestion: data.suggestion,
          riskLevel: data.riskLevel,
          updatedAt: new Date().toISOString(),
        });
        if (updatedItem) {
          showMessage('success', '整改项更新成功');
          setIsFormModalOpen(false);
        } else {
          showMessage('warning', '整改项更新未完成，请重试');
        }
      }
    } catch (error) {
      const action = formMode === 'create' ? '创建' : '更新';
      showMessage('error', `整改项${action}失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  };
  
  // 处理删除确认
  const handleDeleteConfirm = async () => {
    if (itemToDelete) {
      try {
        const success = await deleteRemediationItem(itemToDelete);
        if (success) {
          showMessage('success', '整改项删除成功');
          setItemToDelete(null);
        } else {
          showMessage('warning', '整改项删除未完成，请重试');
        }
      } catch (error) {
        showMessage('error', `整改项删除失败: ${error instanceof Error ? error.message : '未知错误'}`);
      }
    }
  };

  const handleExportReport = () => {
    try {
      exportReport();
    } catch (error) {
      showMessage('error', `整改报告导出失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  };
  
  // 将当前项转换为表单数据
  const currentItemToFormData = (): RemediationFormData | undefined => {
    if (!currentItem) return undefined;
    
    return {
      title: currentItem.title,
      description: currentItem.description,
      suggestion: currentItem.suggestion,
      riskLevel: currentItem.riskLevel,
      item_id: currentItem.item_id,
      plan_id: currentItem.plan_id,
    };
  };
  
  return (
    <div className="h-full flex flex-col">
      <div className="p-4 border-b">
        <div className="flex justify-between items-center mb-6">
          <div className="flex items-center">
            <button
              className="mr-4 p-2 hover:bg-muted rounded-md transition-colors"
              title="返回"
              onClick={() => window.history.back()}
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
              </svg>
            </button>
            <h1 className="text-2xl font-bold">风险台账</h1>
          </div>
          <div className="flex space-x-2">
            <button
              onClick={handleExportReport}
              className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors flex items-center"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
              </svg>
              导出报告
            </button>
            <button
              onClick={openCreateForm}
              className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary-hover transition-colors flex items-center"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
              </svg>
              新增整改项
            </button>
          </div>
        </div>
        
        <StatisticsCards stats={stats} />
      </div>
      
      <div className="flex-1 overflow-y-auto p-4">
        <RemediationList
          onEdit={openEditForm}
          onDelete={openDeleteConfirm}
        />
      </div>
      
      {/* 表单模态框 */}
      <Modal
        isOpen={isFormModalOpen}
        onClose={() => setIsFormModalOpen(false)}
      >
        <RemediationForm
          initialData={currentItemToFormData()}
          onSubmit={handleFormSubmit}
          onCancel={() => setIsFormModalOpen(false)}
          title={formMode === 'create' ? '新增整改项' : '编辑整改项'}
          submitText={formMode === 'create' ? '确认创建' : '确认修改'}
          isFromComplianceItem={false}
        />
      </Modal>
      
      {/* 删除确认对话框 */}
      <ConfirmDialog
        isOpen={isDeleteModalOpen}
        onClose={() => setIsDeleteModalOpen(false)}
        onConfirm={handleDeleteConfirm}
        title="确认删除"
        message="确定要删除此整改项吗？此操作不可撤销。"
      />
    </div>
  );
};

export default RightPanel;
